import React, { useState, useCallback, useEffect } from 'react';
import Header from './Header';
import Footer from './Footer';
import SvgEditor from './SvgEditor';
import SvgPreview from './SvgPreview';
import { Sparkles, ArrowLeftRight } from 'lucide-react';

const SvgViewer = () => {
  const [svgCode, setSvgCode] = useState('');
  const [layout, setLayout] = useState('horizontal'); // horizontal, vertical
  const [isLoading, setIsLoading] = useState(false);

  // 默认示例 SVG
  const defaultSvg = `<svg width="200" height="200" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <linearGradient id="gradient1" x1="0%" y1="0%" x2="100%" y2="100%">
      <stop offset="0%" style="stop-color:#3b82f6;stop-opacity:1" />
      <stop offset="100%" style="stop-color:#8b5cf6;stop-opacity:1" />
    </linearGradient>
  </defs>
  
  <circle cx="100" cy="100" r="80" fill="url(#gradient1)" stroke="#1e40af" stroke-width="3"/>
  <text x="100" y="110" text-anchor="middle" fill="white" font-size="20" font-weight="bold">
    SVG 预览器
  </text>
  
  <g transform="translate(100,100)">
    <g transform="rotate(0)">
      <line x1="0" y1="-60" x2="0" y2="-40" stroke="white" stroke-width="3"/>
    </g>
    <g transform="rotate(45)">
      <line x1="0" y1="-60" x2="0" y2="-50" stroke="white" stroke-width="2"/>
    </g>
    <g transform="rotate(90)">
      <line x1="0" y1="-60" x2="0" y2="-40" stroke="white" stroke-width="3"/>
    </g>
    <g transform="rotate(135)">
      <line x1="0" y1="-60" x2="0" y2="-50" stroke="white" stroke-width="2"/>
    </g>
    <g transform="rotate(180)">
      <line x1="0" y1="-60" x2="0" y2="-40" stroke="white" stroke-width="3"/>
    </g>
    <g transform="rotate(225)">
      <line x1="0" y1="-60" x2="0" y2="-50" stroke="white" stroke-width="2"/>
    </g>
    <g transform="rotate(270)">
      <line x1="0" y1="-60" x2="0" y2="-40" stroke="white" stroke-width="3"/>
    </g>
    <g transform="rotate(315)">
      <line x1="0" y1="-60" x2="0" y2="-50" stroke="white" stroke-width="2"/>
    </g>
  </g>
</svg>`;

  // 初始化时加载默认 SVG
  useEffect(() => {
    setSvgCode(defaultSvg);
  }, []);

  // 处理 SVG 代码变化
  const handleSvgChange = useCallback((newCode) => {
    setSvgCode(newCode);
  }, []);

  // 格式化 SVG 代码
  const handleFormatCode = useCallback(() => {
    if (!svgCode.trim()) return;
    
    setIsLoading(true);
    
    try {
      // 简单的 SVG 格式化
      const parser = new DOMParser();
      const doc = parser.parseFromString(svgCode, 'image/svg+xml');
      const serializer = new XMLSerializer();
      let formatted = serializer.serializeToString(doc);
      
      // 基本的格式化处理
      formatted = formatted
        .replace(/></g, '>\n<')
        .replace(/\s+/g, ' ')
        .trim();
      
      // 简单的缩进处理
      const lines = formatted.split('\n');
      let indentLevel = 0;
      const indentedLines = lines.map(line => {
        const trimmed = line.trim();
        if (trimmed.startsWith('</')) {
          indentLevel = Math.max(0, indentLevel - 1);
        }
        
        const indented = '  '.repeat(indentLevel) + trimmed;
        
        if (trimmed.startsWith('<') && !trimmed.startsWith('</') && !trimmed.endsWith('/>')) {
          indentLevel++;
        }
        
        return indented;
      });
      
      setSvgCode(indentedLines.join('\n'));
    } catch (error) {
      console.error('格式化失败：', error);
    } finally {
      setTimeout(() => setIsLoading(false), 500);
    }
  }, [svgCode]);

  // 切换布局
  const toggleLayout = () => {
    setLayout(prev => prev === 'horizontal' ? 'vertical' : 'horizontal');
  };

  const isHorizontal = layout === 'horizontal';

  return (
    <div className="min-h-screen bg-gradient-to-br from-indigo-50 via-white to-purple-50">
      <Header />
      
      {/* 主要内容区域 */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* 工具栏 */}
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center space-x-3">
            <div className="flex items-center space-x-2">
              <Sparkles className="w-5 h-5 text-blue-600" />
              <h2 className="text-xl font-semibold text-gray-900">实时预览</h2>
            </div>
            <div className="text-sm text-gray-500">
              输入 SVG 代码，立即查看效果
            </div>
          </div>
          
          <button
            onClick={toggleLayout}
            className="flex items-center space-x-2 px-4 py-2 bg-white/80 backdrop-blur-sm border border-gray-200/50 rounded-xl hover:bg-white hover:shadow-md transition-all duration-200"
          >
            <ArrowLeftRight className={`w-4 h-4 ${isHorizontal ? '' : 'rotate-90'}`} />
            <span>{isHorizontal ? '水平布局' : '垂直布局'}</span>
          </button>
        </div>

        {/* 编辑器和预览区域 */}
        <div className={`grid gap-6 ${isHorizontal ? 'grid-cols-1 lg:grid-cols-2' : 'grid-cols-1'}`}>
          {/* SVG 编辑器 */}
          <div className={`${isHorizontal ? '' : 'order-2'}`}>
            <SvgEditor 
              svgCode={svgCode}
              onSvgChange={handleSvgChange}
              onFormatCode={handleFormatCode}
            />
          </div>
          
          {/* SVG 预览 */}
          <div className={`${isHorizontal ? '' : 'order-1'}`}>
            <SvgPreview svgCode={svgCode} />
          </div>
        </div>

        {/* 功能说明 */}
        <div className="mt-12 bg-white/60 backdrop-blur-sm rounded-2xl p-6 border border-gray-200/50">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">功能特性</h3>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <div className="flex items-start space-x-3">
              <div className="flex-shrink-0 w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center">
                <Sparkles className="w-4 h-4 text-blue-600" />
              </div>
              <div>
                <h4 className="font-medium text-gray-900">实时预览</h4>
                <p className="text-sm text-gray-600">输入代码即时查看 SVG 效果</p>
              </div>
            </div>
            
            <div className="flex items-start space-x-3">
              <div className="flex-shrink-0 w-8 h-8 bg-green-100 rounded-lg flex items-center justify-center">
                <ArrowLeftRight className="w-4 h-4 text-green-600" />
              </div>
              <div>
                <h4 className="font-medium text-gray-900">灵活布局</h4>
                <p className="text-sm text-gray-600">支持水平和垂直布局切换</p>
              </div>
            </div>
            
            <div className="flex items-start space-x-3">
              <div className="flex-shrink-0 w-8 h-8 bg-purple-100 rounded-lg flex items-center justify-center">
                <div className="w-4 h-4 bg-purple-600 rounded"></div>
              </div>
              <div>
                <h4 className="font-medium text-gray-900">多种背景</h4>
                <p className="text-sm text-gray-600">透明、纯色、棋盘等背景选择</p>
              </div>
            </div>
          </div>
        </div>
      </main>

      <Footer />
      
      {/* 加载状态 */}
      {isLoading && (
        <div className="fixed inset-0 bg-black/20 backdrop-blur-sm flex items-center justify-center z-50">
          <div className="bg-white rounded-xl p-6 shadow-2xl">
            <div className="flex items-center space-x-3">
              <div className="w-6 h-6 border-2 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
              <span className="text-gray-900">正在格式化...</span>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default SvgViewer;
